package com.rocksdata.mc.business;

import android.content.Context;
import android.text.TextUtils;
import com.alibaba.fastjson.JSON;
import com.ctz.commonframe.utils.ApplicationUtil;
import com.ctz.commonframe.utils.Logger;
import com.ctz.commonframe.utils.SharedPrefrencesUtil;
import com.rocksdata.mc.BuildConfig;
import com.rocksdata.mc.R;
import com.rocksdata.mc.SharedPreferencesKey;
import com.rocksdata.mc.entity.VersionInfo;
import com.rocksdata.mc.http.HttpClient;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.util.List;

public class VersionManager implements BusinessInterface.IVersionManager {
    private static final String URL_GET_LATEST_VERSION_INFO = BuildConfig.HOST + "/version/1";
//    private static final String URL_GET_LATEST_VERSION_INFO = "http://192.168.1.13:8000/api/version/1";

    private static BusinessInterface.IVersionManager instance;

    static synchronized BusinessInterface.IVersionManager getInstance() {
        if (instance == null)
            instance = new VersionManager();
        return instance;
    }

    private VersionManager () {

    }

    public static VersionInfo getVersionInfo () {
        String str = (String) SharedPrefrencesUtil.get(SharedPreferencesKey.KEY_VERSION_INFO, null);
        if (TextUtils.isEmpty(str))
            return null;
        return JSON.parseObject(str, VersionInfo.class);
    }

    private static void saveVersionInfo (VersionInfo info) {
        if (info == null)
            return;
        SharedPrefrencesUtil.put(SharedPreferencesKey.KEY_VERSION_INFO, JSON.toJSONString(info));
    }

    /**
     * 是否最新版本
     *
     * @param context 上下文
     * @param info 版本信息
     * @return true为最新版本，false为老版本
     */
    public static boolean isLatestVersion(Context context, VersionInfo info) {
        int currentVersionCode = ApplicationUtil.getAppVersionCode(context);
        return info != null && info.getVersionCode() > currentVersionCode;
    }

    /**
     * 获取版本对应apk文件名
     *
     * @param context 上下文
     * @param versionName 版本名稱
     * @return 文件名
     */
    private static String getApkFileName(Context context, String versionName) {
        return context.getString(R.string.app_name) + "_" + versionName + ".apk";
    }

    @Override
    public void getLatestVersionInfo(final BusinessInterface.OnBusinessResultListener listener) {
        HttpClient.get(URL_GET_LATEST_VERSION_INFO, null, VersionInfo.class, new HttpClient.OnHttpResultListener<VersionInfo>() {
            @Override
            public void onResult(boolean isSuccess, List<VersionInfo> data, String msg) {
                if (isSuccess) {
                    VersionManager.saveVersionInfo(data.get(0));
                    listener.onBusinessResult(true, data.get(0), null);
                } else {
                    Logger.e("getLatestVersionInfo failure:" + msg);
                    listener.onBusinessResult(false, null, null);
                }
            }
        });
    }

    @Override
    public void updateVersion(Context context, VersionInfo info, Callback.ProgressCallback<File> callback) {
        String fileName = getApkFileName(context, info.getVersionName());
        final String savePath = ApplicationUtil.getApkSavePath(context, fileName);
        Logger.e("VersionManager", "file name:" + fileName + ", file path:" + savePath);
        File file= new File(savePath);
        if (!file.getParentFile().exists())
            file.getParentFile().mkdirs();
        if(file.exists()){
            ApplicationUtil.installApk(context, savePath);
        }else{
            RequestParams requestParams = new RequestParams(info.getVersionURL());
            requestParams.setSaveFilePath(savePath);
            requestParams.setAutoRename(true);
            x.http().get(requestParams, callback);
        }
    }
}
